<template>
    <div class="page">
        <div class="title">居民管理</div>
        <el-form :inline="true">
            <el-form-item label="楼栋">
                <CascaderBuilding clearable @change="onSearch" v-model="params.buildingid" type="single"></CascaderBuilding>
            </el-form-item>
            <el-form-item label="姓名">
                <el-input style="width:180px;" v-model="params.name" placeholder="请输入姓名" clearable />
            </el-form-item>
            <el-form-item label="电话">
                <el-input style="width:180px;" v-model="params.mobile" placeholder="请输入电话" clearable />
            </el-form-item>
            <el-form-item label="">
                <el-button type="primary" @click="onSearch">搜索</el-button>
            </el-form-item>
        </el-form>
        <div class="buttons">
            <el-button @click="add" type="primary">添加</el-button>
            <el-button @click="deleteMultipleHandle" type="danger">批量删除</el-button>
            <el-button type="success">批量审核</el-button>
        </div>
        <div class="table">

            <el-table :header-cell-style="{background:'#fafafa'}"  @selection-change="handleSelectionChange" :data="data.list" style="width: 100%">
                <el-table-column fixed="left" type="selection"  width="30" />
                <el-table-column fixed="left" prop="id" label="ID" width="60" />
                <el-table-column fixed="left" prop="photo" label="头像" width="70">
                    <template #default="scope">

                        <el-image style="width:40px; height:40px" preview-teleported
                            :src="IMG_BASE_URL + scope.row.photo" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                            :preview-src-list="[IMG_BASE_URL + scope.row.photo]" show-progress :initial-index="4"
                            fit="cover" />

                    </template>
                </el-table-column>
                <el-table-column  fixed="left"  prop="name"  width="80" label="姓名" />
                <el-table-column prop="usertypeName"  width="60" label="类型" />
                <el-table-column prop="sex" width="60" label="性别" >
                   <template #default="scope">
                       {{scope.row.sex==1?'男':'女'}}
                   </template>
                </el-table-column>
                <el-table-column prop="cardid" width="180"  label="身份证号" />
                <el-table-column prop="mobile" width="130"  label="手机号" />
                <el-table-column prop="usernative" width="100" label="籍贯" />
                <el-table-column prop="nation" label="民族" />
                <el-table-column prop="building" min-width="200"  label="小区" />
                <el-table-column prop="houseno" label="房间号" />
                <el-table-column prop="stateName" label="审核状态" />
                <el-table-column prop="addtime"  width="150" label="添加时间">
                  <template #default="scope">
                    {{ formatDate(scope.row.addtime) }}
                  </template>
                </el-table-column>

                <el-table-column width="160" fixed="right" label="操作">
                    <template #default="scope">
                        <el-button type="success" @click="edit(scope.row)">编辑</el-button>
                        <el-button  type="danger" @click="del(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <div class="pageinfo">
            <el-pagination v-model:current-page="params.page" v-model:page-size="params.psize"
                :page-sizes="[10, 30, 50, 100, 400]" background size="small"
                layout="total, sizes, prev, pager, next, jumper" :total="data.counts" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />

        </div>
        <Add :buildingid="buildingid" v-if="dialogVisible" @close="closeHandle" :id="editUserId" :dialogVisible="dialogVisible"></Add>
    </div>
</template>
<script setup lang='ts'>
import type { UserInfo, UserListResponse, UserParams } from '@/apis/userinfo/type';
import { deleteUserById, deleteUserByIds, getUserinfoList } from '@/apis/userinfo/userinfo';
import { ref, reactive, toRefs, toRef } from 'vue';
import Add from '@/components/userinfo/Add.vue';
import { ElMessage, ElMessageBox, dayjs } from 'element-plus';


const dialogVisible = ref(false);

const IMG_BASE_URL = ref(import.meta.env.VITE_IMG_URL);

const params = reactive<UserParams>({
    key: "",
    name: "",
    mobile: "",
    buildingid:undefined,
    page: 1,
    psize: 10
})

const data = reactive<UserListResponse>({
    counts: 0,
    list: [],
})

//格式化时间
const formatDate=(time:string)=>{

  return  dayjs(time).format("YYYY-MM-DD HH:mm");
}

//    const list= toRef(data,"list"); //创建一个 ref 对象，其value值指向另一个reactive对象中的某个属性。
//const {list,counts}= toRefs(data);

//删除居民
const del = async (id: number) => {

    const confirm = await ElMessageBox.confirm(
        '确定要删除该居民吗?',
        '提示',
        {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).catch(() => undefined)

    if (!confirm) return ElMessage.info('已取消删除');
    await deleteUserById(id);
    getUserData();



}
//批量删除
const deleteMultipleHandle = async () => { 

    if (!multipleSelection.value.length)  return  ElMessage.error('请选择要删除的记录');
    const confirm = await ElMessageBox.confirm(
        '确定要删除选中的居民吗?',
        '提示',
        {
            confirmButtonText: '确定删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).catch(() => undefined)
    if (!confirm) return ElMessage.info('已取消删除');


    let ids:number[]=multipleSelection.value.map(item => item.id);
     await deleteUserByIds(ids).catch(() => undefined);
     getUserData();



};

const multipleSelection=ref<UserInfo[]>([]);

const handleSelectionChange = (val: UserInfo[]) => {
  multipleSelection.value = val
}

//添加
const add = () => {

    console.log("添加");
    editUserId.value = 0;
    buildingid.value=0;
    dialogVisible.value = true;

}
//编辑

const editUserId = ref<number | undefined>(0);
const buildingid= ref<number | undefined>(0);
const edit = (row: UserInfo) => {

    console.log("编辑", row);

    editUserId.value = row.id;
    buildingid.value=row.buildingid;
    dialogVisible.value = true;
}

const closeHandle = (value: boolean) => {
    dialogVisible.value = false;
    if (value) {
        getUserData();
    }

}

const onSearch = () => {
    params.page = 1;
    getUserData();
}

const getUserData = async () => {

    const res = await getUserinfoList(params);
    data.list = res.data.list;
    data.counts = res.data.counts;

}

getUserData();

const handleSizeChange = (val: number) => {
    console.log(`${val} items per page`)
    params.psize = val;
    getUserData();
}
const handleCurrentChange = (val: number) => {
    console.log(`current page: ${val}`)
    params.page = val;
    getUserData();
}



</script>
<style scoped lang='less'>

</style>